package com.hui.config.security.wechat;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

import java.util.Collections;

public class AuthCenterAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        AuthCenterAuthenticationToken authenticationToken = (AuthCenterAuthenticationToken) authentication;

        //调用AuthCenter进行认证

        //微信已经关联手机号，则后台使用手机号进行默认登录
        //默认登录

        //认证通过后查询用户信息

        //调用自定义的userDetailsService认证
//        UserDetails user = userDetailsService.loadUserByUsername(publicUserEntity.getUsername());

        UserDetails user = new User("zhangsan", "123456", Collections.emptySet());

        if (user == null || StringUtils.isEmpty(user.getUsername())) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        //如果user不为空重新构建SmsCodeAuthenticationToken（已认证）
        AuthCenterAuthenticationToken authenticationResult = new AuthCenterAuthenticationToken(user, user.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    /**
     * 只有Authentication为MobileAuthenticationToken使用此Provider认证
     *
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return AuthCenterAuthenticationToken.class.isAssignableFrom(authentication);
        //return "mobile".equals(authentication.get)
    }


}
